<!DOCTYPE html>
<html>
<head>
	<title>ball</title>
	<style type="text/css">
		.ball{
			margin-left:0;
			width:40px;
			height:40px;
			border-radius:50%;
		}
		.ball1{
			background-color: red;
		}
		.ball2{
			background-color: yellow;
		}
		.ball3{
			background-color: green;
		}
	</style>
</head>
<body>
	<div class="ball ball1"></div>
	<div class="ball ball2"></div>
	<div class="ball ball3"></div>

	<script type="text/javascript">
		var ball1 = document.querySelector('.ball1');
		var ball2 = document.querySelector('.ball2');
		var ball3 = document.querySelector('.ball3');

		// var sheet = ball1.sheet; //待验证
		// var sheet = document.styleSheets[0];
		// var rule = sheet.cssRules[1];
		// console.log(rule.cssText);

		// rule.style.marginLeft = '10px';
		// console.log(rule.cssText);

		// ball1.style.marginLeft = '10px';

		// var marginLeft = parseInt(ball1.currentStyle ? ball1.currentStyle.marginLeft : window.getComputedStyle(ball1).marginLeft);
		// console.log('marginLeft is: ' + marginLeft + '\n');


		// function animate(ball,distance,callback) {
		// 	setTimeout(function() {
		// 		var marginLeft = parseInt(ball.currentStyle ? ball.currentStyle.marginLeft : window.getComputedStyle(ball).marginLeft);
		// 		// console.log(marginLeft + ' & dis is:' + distance);

		// 		if(marginLeft == distance){
		// 			callback && callback();
		// 		}else{
		// 			if(marginLeft < distance){
		// 				marginLeft++;
		// 			}else{
		// 				marginLeft--;
		// 			}
		// 			ball.style.marginLeft = marginLeft + 'px';
		// 			animate(ball,distance,callback);
		// 		}
		// 	}, 13)
		// }

		// animate(ball1,100,function(){
		// 	animate(ball2,200,function(){
		// 		animate(ball3,300,function(){
		// 			animate(ball3,150,function(){
		// 				animate(ball2,150,function(){
		// 					animate(ball1,150,function(){
		// 						console.log('动画完毕');
		// 					});
		// 				});
		// 			});
		// 		});
		// 	});
		// });

		function promiseAnimate(ball,distance){
			return new Promise((resolve,reject) => {

				function _animate() {
					setTimeout(function() {
						var marginLeft = parseInt(ball.currentStyle ? ball.currentStyle.marginLeft : window.getComputedStyle(ball).marginLeft);

						if(marginLeft == distance){
							resolve();
						}else{
							if(marginLeft < distance){
								marginLeft++;
							}else{
								marginLeft--;
							}
							ball.style.marginLeft = marginLeft + 'px';
							_animate();
						}
					}, 13)
				}
				_animate();

			})
		}

		promiseAnimate(ball1,100)
			.then(() => {
				return promiseAnimate(ball2,200);
			})
			.then(() => {
				return promiseAnimate(ball3,300);
			})
			.then(() => {
				return promiseAnimate(ball3,150);
			})
			.then(() => {
				return promiseAnimate(ball2,150);
			})
			.then(() => {
				return promiseAnimate(ball1,150);
			})

	</script>
</body>
</html>